package com.whiteape.book.core.engine.helper;

import android.util.Log;

import com.whiteape.book.net.RetrofitHelper;
import com.whiteape.book.utils.FileUtils;
import com.whiteape.book.utils.StringUtils;
import com.whiteape.book.utils.URLUtils;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;

public class JavaBridge {

    private Context rhino;
    private Scriptable scope;
    private int lineNo;

    public JavaBridge(Context rhino, Scriptable scope, int linNo) {
        this.rhino = rhino;
        this.scope = scope;
        this.lineNo = linNo;

    }

    public void loadUrl(String url) {
        Log.e("TWTW", "LLLLLLLLLLLLLLoad url" + url);

        String content = FileUtils.getCachedJsContent(url);
//        System.out.println("HHH content is " + content);
        if (StringUtils.isEmpty(content)) {
            content = getUrl(url);
//            System.out.println("YYY content now is " + content);
        }
        FileUtils.cacheJsRemoteFile(url, content);
        rhino.evaluateString(scope, content, "lib" + lineNo, lineNo, null);
        lineNo++;
    }

    public String getUrl(String url) {
        try {
            return RetrofitHelper.getInstance().getHttpApiImpl(URLUtils.getBaseUrl(url))
                    .download(url).execute().body().string();

        } catch (Exception e) {
            return "";
        }
    }
}
